const { prisma } = require('../config/prisma');

class ExposurePrisma {
  // 转换BigInt为字符串的工具方法
  static convertBigInt(obj) {
    if (!obj) return obj;
    
    if (Array.isArray(obj)) {
      return obj.map(item => this.convertBigInt(item));
    }
    
    if (obj instanceof Date) {
      return obj;
    }
    
    if (typeof obj === 'object') {
      const converted = {};
      for (const key in obj) {
        if (typeof obj[key] === 'bigint') {
          converted[key] = obj[key].toString();
        } else if (obj[key] instanceof Date) {
          converted[key] = obj[key];
        } else if (typeof obj[key] === 'object' && obj[key] !== null) {
          converted[key] = this.convertBigInt(obj[key]);
        } else {
          converted[key] = obj[key];
        }
      }
      return converted;
    }
    
    return obj;
  }
  // 创建曝光帖子
  static async createPost(data) {
    const post = await prisma.exposure_posts.create({
      data: {
        user_id: data.user_id,
        content: data.content,
        images: data.images ? JSON.stringify(data.images) : null,
      },
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true,
          }
        }
      }
    });

    return this.convertBigInt(post);
  }

  // 获取曝光帖子列表
  static async getPostsList(page = 1, pageSize = 10) {
    const skip = (page - 1) * pageSize;
    
    const [posts, total] = await prisma.$transaction([
      prisma.exposure_posts.findMany({
        skip,
        take: pageSize,
        orderBy: {
          created_at: 'desc'
        },
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true,
            }
          }
        }
      }),
      prisma.exposure_posts.count()
    ]);

    // 解析图片JSON并转换BigInt
    const postsWithParsedImages = posts.map(post => this.convertBigInt({
      ...post,
      images: post.images ? JSON.parse(post.images) : [],
    }));

    return {
      posts: postsWithParsedImages,
      pagination: {
        current_page: page,
        page_size: pageSize,
        total_count: total,
        total_pages: Math.ceil(total / pageSize)
      }
    };
  }

  // 获取单个帖子详情
  static async getPostById(postId) {
    const post = await prisma.exposure_posts.findUnique({
      where: { id: BigInt(postId) },
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true,
          }
        }
      }
    });

    if (post) {
      post.images = post.images ? JSON.parse(post.images) : [];
      return this.convertBigInt(post);
    }

    return post;
  }

  // 点赞/取消点赞
  static async toggleLike(postId, userId) {
    const existingLike = await prisma.exposure_likes.findUnique({
      where: {
        post_id_user_id: {
          post_id: BigInt(postId),
          user_id: BigInt(userId)
        }
      }
    });

    if (existingLike) {
      // 取消点赞
      await prisma.$transaction([
        prisma.exposure_likes.delete({
          where: { id: existingLike.id }
        }),
        prisma.exposure_posts.update({
          where: { id: BigInt(postId) },
          data: { like_count: { decrement: 1 } }
        })
      ]);
      return { liked: false };
    } else {
      // 添加点赞
      await prisma.$transaction([
        prisma.exposure_likes.create({
          data: {
            post_id: BigInt(postId),
            user_id: BigInt(userId)
          }
        }),
        prisma.exposure_posts.update({
          where: { id: BigInt(postId) },
          data: { like_count: { increment: 1 } }
        })
      ]);
      return { liked: true };
    }
  }

  // 检查用户是否已点赞
  static async checkUserLiked(postId, userId) {
    const like = await prisma.exposure_likes.findUnique({
      where: {
        post_id_user_id: {
          post_id: BigInt(postId),
          user_id: BigInt(userId)
        }
      }
    });
    return !!like;
  }

  // 创建评论
  static async createComment(data) {
    const comment = await prisma.$transaction(async (tx) => {
      const newComment = await tx.exposure_comments.create({
        data: {
          post_id: BigInt(data.post_id),
          user_id: BigInt(data.user_id),
          content: data.content,
        },
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true,
            }
          }
        }
      });

      // 更新帖子评论数量
      await tx.exposure_posts.update({
        where: { id: BigInt(data.post_id) },
        data: { comment_count: { increment: 1 } }
      });

      return newComment;
    });

    return this.convertBigInt(comment);
  }

  // 获取帖子评论列表
  static async getCommentsByPostId(postId, page = 1, pageSize = 20) {
    const skip = (page - 1) * pageSize;
    
    const [comments, total] = await prisma.$transaction([
      prisma.exposure_comments.findMany({
        where: { post_id: BigInt(postId) },
        skip,
        take: pageSize,
        orderBy: {
          created_at: 'asc'
        },
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true,
            }
          }
        }
      }),
      prisma.exposure_comments.count({
        where: { post_id: BigInt(postId) }
      })
    ]);

    return {
      comments: this.convertBigInt(comments),
      pagination: {
        current_page: page,
        page_size: pageSize,
        total_count: total,
        total_pages: Math.ceil(total / pageSize)
      }
    };
  }

  // 获取用户发布的帖子
  static async getUserPosts(userId, page = 1, pageSize = 10) {
    const skip = (page - 1) * pageSize;
    
    const [posts, total] = await prisma.$transaction([
      prisma.exposure_posts.findMany({
        where: { user_id: BigInt(userId) },
        skip,
        take: pageSize,
        orderBy: {
          created_at: 'desc'
        },
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true,
            }
          }
        }
      }),
      prisma.exposure_posts.count({
        where: { user_id: BigInt(userId) }
      })
    ]);

    const postsWithParsedImages = posts.map(post => this.convertBigInt({
      ...post,
      images: post.images ? JSON.parse(post.images) : [],
    }));

    return {
      posts: postsWithParsedImages,
      pagination: {
        current_page: page,
        page_size: pageSize,
        total_count: total,
        total_pages: Math.ceil(total / pageSize)
      }
    };
  }

  // 更新分享数量
  static async incrementShareCount(postId) {
    const result = await prisma.exposure_posts.update({
      where: { id: BigInt(postId) },
      data: { share_count: { increment: 1 } }
    });
    return this.convertBigInt(result);
  }

  // 管理员获取所有帖子列表（含搜索和筛选）
  static async getAdminPostsList(filters = {}) {
    const {
      page = 1,
      pageSize = 10,
      search,
      startDate,
      endDate,
      sortBy = 'created_at',
      sortOrder = 'desc'
    } = filters;

    const skip = (page - 1) * pageSize;
    const where = {};

    // 搜索条件
    if (search) {
      where.OR = [
        { content: { contains: search } },
        { users: { nickname: { contains: search } } }
      ];
    }

    // 日期范围筛选
    if (startDate || endDate) {
      where.created_at = {};
      if (startDate) where.created_at.gte = new Date(startDate);
      if (endDate) where.created_at.lte = new Date(endDate);
    }

    const [posts, total] = await prisma.$transaction([
      prisma.exposure_posts.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: {
          [sortBy]: sortOrder
        },
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true,
              phone_number: true
            }
          },
          exposure_comments: {
            select: {
              id: true,
              content: true,
              created_at: true,
              users: {
                select: {
                  id: true,
                  nickname: true
                }
              }
            },
            orderBy: {
              created_at: 'desc'
            },
            take: 3 // 只显示最新的3条评论
          }
        }
      }),
      prisma.exposure_posts.count({ where })
    ]);

    // 解析图片JSON并转换BigInt
    const postsWithParsedImages = posts.map(post => this.convertBigInt({
      ...post,
      images: post.images ? JSON.parse(post.images) : [],
    }));

    return {
      posts: postsWithParsedImages,
      pagination: {
        current_page: page,
        page_size: pageSize,
        total_count: total,
        total_pages: Math.ceil(total / pageSize)
      }
    };
  }

  // 管理员删除帖子
  static async deletePost(postId) {
    return await prisma.$transaction(async (tx) => {
      // 删除评论
      await tx.exposure_comments.deleteMany({
        where: { post_id: BigInt(postId) }
      });

      // 删除点赞
      await tx.exposure_likes.deleteMany({
        where: { post_id: BigInt(postId) }
      });

      // 删除帖子
      const result = await tx.exposure_posts.delete({
        where: { id: BigInt(postId) }
      });

      return this.convertBigInt(result);
    });
  }

  // 管理员更新帖子内容
  static async updatePost(postId, updateData) {
    const data = {};
    if (updateData.content !== undefined) {
      data.content = updateData.content;
    }
    if (updateData.images !== undefined) {
      data.images = updateData.images ? JSON.stringify(updateData.images) : null;
    }

    const result = await prisma.exposure_posts.update({
      where: { id: BigInt(postId) },
      data,
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true,
          }
        }
      }
    });

    return this.convertBigInt({
      ...result,
      images: result.images ? JSON.parse(result.images) : []
    });
  }

  // 管理员删除评论
  static async deleteComment(commentId) {
    const comment = await prisma.exposure_comments.findUnique({
      where: { id: BigInt(commentId) }
    });

    if (!comment) {
      throw new Error('评论不存在');
    }

    await prisma.$transaction([
      prisma.exposure_comments.delete({
        where: { id: BigInt(commentId) }
      }),
      prisma.exposure_posts.update({
        where: { id: comment.post_id },
        data: { comment_count: { decrement: 1 } }
      })
    ]);

    return this.convertBigInt(comment);
  }

  // 获取统计信息
  static async getStats() {
    const [
      totalPosts,
      totalComments,
      totalLikes,
      todayPosts
    ] = await prisma.$transaction([
      prisma.exposure_posts.count(),
      prisma.exposure_comments.count(),
      prisma.exposure_likes.count(),
      prisma.exposure_posts.count({
        where: {
          created_at: {
            gte: new Date(new Date().setHours(0, 0, 0, 0))
          }
        }
      })
    ]);

    return {
      total_posts: totalPosts,
      total_comments: totalComments,
      total_likes: totalLikes,
      today_posts: todayPosts
    };
  }
}

module.exports = ExposurePrisma;